#!/bin/bash

echo "***********************************"
echo "*                                 *"
echo "*    video converter for N900     *"
echo "*                                 *"
echo "***********************************"



INPUT_DIR=.
OUTPUT_DIR=$INPUT_DIR/converted



# do not allow concurrency 
if [ -e "$INPUT_DIR/.lock" ]; then
  exit 1
else
  touch "$INPUT_DIR/.lock"
fi

function convert_file {
	original_def=$2
	original_file=$1
	converted_file="$OUTPUT_DIR/$original_file.mp4"

	if [ -e "$converted_file" ]; then
		return 1
	fi
	
 	if [ $original_def == "mpeg" ]; then
		SIZE="400x480"
	elif [ $original_def == "dvd" ]; then
		SIZE="592x480"
	elif [ $original_def == "hd" ]; then
		SIZE="640x480"
	elif [ $original_def == "other" ]; then
		SIZE="848x480"
	else
		echo "format $original_def inconnu"
		return 1
	fi

	echo $converted_file > .work_in_progress
	(ffmpeg -i "$original_file"  -acodec aac -strict experimental  -vcodec libx264  -vpre medium -vprofile baseline  -crf 18 -maxrate 1000k -bufsize 2000k -threads 0 -flags2 -fastpskip  -s "$SIZE" "$converted_file" ) &
	echo $! > .work_pid
	wait        
	if [ $? -eq 0 ]; then
		rm "$original_file"
	fi
	rm .work_pid
	rm .work_in_progress


}

function clean_shutdown {
  echo "shutdown sequence..."
  if [ -e ".work_pid" ]; then
	kill `cat .work_pid`
	rm .work_pid
  fi
  if [ -e .work_in_progress ]; then
        rm "`cat .work_in_progress`"
	rm .work_in_progress
  fi
  rm "$INPUT_DIR/.lock"
  exit 1
}

trap 'clean_shutdown' SIGTERM SIGINT SIGHUP



find $INPUT_DIR -maxdepth 1 -type f \( -name "France 3*.ts" -o -name "France 4*.ts" -o -name "France 5*.ts" -o -name "La Chaîne*.ts" -o -name "NT1*.ts" -o -name "TMC*.ts" \) -print | ( while read i; do convert_file "$i" mpeg; done )

find $INPUT_DIR -maxdepth 1 -type f \( -name "DirectStar*.ts" -o -name "RTL9*.ts" -o -name "AB*.ts" -o -name "France Ô*.ts" \) -print | ( while read i; do convert_file "$i" dvd; done )

find $INPUT_DIR -maxdepth 1 -type f \( -name "Arte*.ts" -o -name "Direct 8*.ts" -o -name "France 2*.ts" -o -name "NRJ*.ts" \) -print | ( while read i; do convert_file "$i" hd; done )

# this just for any extra video i could put in the process directory
find $INPUT_DIR -maxdepth 1 -type f \( -name "*.mpeg" -o -name "*.vob" -o -name "*.mpg" -o -name "*.avi" -o -name "*.mp4" -o -name "*.ogg" \) | ( while read i; do convert_file "$i" other; done )

rm "$INPUT_DIR/.lock"
